<template>
  <div>
    <HeaderComponent /> <!-- 顶部导航栏 -->

    <div id="BackLink">
      <router-link to="/main">返回主菜单</router-link>
    </div>

    <div id="Catalog">
      <!-- 只有当 category 存在时才渲染 category.name -->
      <h2 v-if="category" v-text="category.categoryName"></h2>
      
      <!-- 只有当 category 和 productList 存在时才渲染表格 -->
      <table v-if="category && category.productList">
        <thead>
          <tr>
            <th>Product ID</th>
            <th>Name</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="product in category.productList" :key="product.productid"
              @click="goToProduct(product.productid)">
            <td>{{ product.productid }}</td>
            <td>{{ product.name }}</td>
          </tr>
        </tbody>
      </table>
    </div>

    <FooterComponent /> <!-- 底部信息 -->
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import { getCategoryProducts } from "@/api/Category";
import HeaderComponent from '@/components/Header.vue';
import FooterComponent from '@/components/Footer.vue';
import "@/assets/css/global.css";

const category = ref(null);
const route = useRoute();
const router = useRouter();

// 获取分类数据
const fetchCategory = async () => {
  try {
    const response = await getCategoryProducts(route.params.categoryId);
    if (response.status === 0) {
      category.value = response.data;
      console.log('分类数据:', JSON.stringify(category.value, null, 2));
    } else {
      console.error('后端返回错误:', response.message);
    }
  } catch (error) {
    console.error("获取分类数据失败:", error);
  }
};

// 跳转到商品详情页
const goToProduct = (productId) => {
  router.push(`/product/${route.params.categoryId}/${productId}`);
};

onMounted(fetchCategory);
</script>